package com.bw.gmall.realtime.common.Util;

import com.bw.gmall.realtime.common.constant.Constant;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;


import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.bw.gmall.realtime.common.constant.Constant.*;

public class JdbcUtil {

    public static Connection getMysqlConnection() throws ClassNotFoundException, SQLException {

        Class.forName(MYSQL_DRIVER);
        return DriverManager.getConnection(MYSQL_UrL,MYSQL_USER_NAME,MYSQL_USER_PASSWORD);
    }


    public static <T> List<T> queryList(Connection conn, String querySql,Class<T> tClass,Boolean ...isUnderlineToCamel) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {

        boolean defaultIsUToC = false;

        if(isUnderlineToCamel.length > 0){
            defaultIsUToC = isUnderlineToCamel[0];
        }

        List<T> result = new ArrayList<>();

//        1.预编译
        PreparedStatement ps = conn.prepareStatement(querySql);
//        2.执行结果，获得结果集
        ResultSet resultSet = ps.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
//        3.解析结果集，把数据封装到一个list集合中

        while (resultSet.next()){
//            变量到一行数据，把数据封装到一个T 类型对象

            T t = tClass.newInstance();

//            遍历每一行数据

            for (int i=1 ;i <= metaData.getColumnCount(); i++){
//                获取列名
//                获取列值
                String columnLabel = metaData.getColumnLabel(i);
                Object value = resultSet.getObject(columnLabel);

                if(defaultIsUToC){

                    columnLabel = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tClass.getCanonicalName());
                }

                BeanUtils.setProperty(t,columnLabel,value);

            }

            result.add(t);

        }

        return result;

    };






    public static void closeConnection(Connection conn) throws SQLException {

        if(conn != null){
            conn.close();
        }

    }

}
